const axios = require('axios')
const sign = require('./sign/xhs/index');
const minimist = require('minimist');

const args = minimist(process.argv.slice(2));
console.log("获取到的参数：" + JSON.stringify(args))

// 访问解析后的参数
console.log('api:', args.api); // 输出: John
console.log('reqData:', args.data);   // 输出: 30
function getNote(api, data) {
    console.log("请求api" + api)
    console.log("请求data" + data)
    const baseUrl = "https://edith.xiaohongshu.com"
    const {traceId, xs, xsCommon, xt, cookie} = sign(api, data)

    return axios({
        url: baseUrl + api,
        method: 'post',
        headers: {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'X-B3-Traceid': traceId,
            'X-S': xs,
            'X-S-Common': xsCommon,
            'X-T': xt,
            'Cookie': cookie
        },
        data
    });
}

function isString(obj) { //判断对象是否是字符串
    return Object.prototype.toString.call(obj) === "[object String]";
}

function getScriptNote(api, data) {
    console.log("请求api" + api)
    console.log("请求data" + data)
    const baseUrl = "https://edith.xiaohongshu.com"
    const {traceId, xs, xsCommon, xt, cookie} = sign(api, data)

    return axios({
        url: baseUrl + api,
        method: 'post',
        headers: {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'X-B3-Traceid': traceId,
            'X-S': xs,
            'X-S-Common': xsCommon,
            'X-T': xt,
            'Cookie': cookie
        },
        data
    });
}

const run = async () => {
    let reqData = JSON.parse(args.data)
    const {status, data} = await getScriptNote(args.api, reqData)
    if (status === 200) {
        if (isString(data)) {
            console.log("xhs=" + data)
        } else {
            console.log("xhs=" + JSON.stringify(data))
        }

    } else {
        throw new Error('获取失败')
    }
}
run()

const controller = async (ctx) => {

    const {noteId} = ctx.request.query
    if (noteId) {
        try {
            const {status, data} = await getNote(noteId)
            if (status === 200 && data.code === 0) {
                ctx.status = 200
                ctx.body = {
                    code: 200,
                    msg: 'success',
                    data: data.data
                }
            } else {
                throw new Error('获取失败')
            }
        } catch (error) {
            ctx.status = 500
            ctx.body = {
                code: 500,
                msg: '服务错误',
                error
            }
        }
        return
    }
    ctx.status = 400
    ctx.body = {
        code: 400,
        msg: 'noteId 不能为空'
    }
}

module.exports = controller
